/*
 *
 *  * Copyright 2022  腾羚智能, Inc. All rights reserved.
 *
 */

package com.ruoyi.framework.handler.dbHandler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ruoyi.framework.config.properties.MybatisPlusAutoFillProperties;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * 自定义填充公共字段
 *
 *
 *
 * <p>
 */
public class DateMetaObjectHandler implements MetaObjectHandler {

    private MybatisPlusAutoFillProperties autoFillProperties;

    public DateMetaObjectHandler(MybatisPlusAutoFillProperties autoFillProperties) {
        this.autoFillProperties = autoFillProperties;
    }

    /**
     * 是否开启了插入填充
     */
    @Override
    public boolean openInsertFill() {
        return this.autoFillProperties.getEnableInsertFill();
    }

    /**
     * 是否开启了更新填充
     */
    @Override
    public boolean openUpdateFill() {
        return this.autoFillProperties.getEnableUpdateFill();
    }

    /**
     * 获取用户id
     */
    public Long getUserId() {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes()))
                    .getRequest();
            String userId = request.getHeader("x-userid-header");
            return StringUtils.isBlank(userId) ? null : Long.valueOf(userId);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 插入填充，字段为空自动填充
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        // 创建人
        Long userId = this.getUserId();
        if (userId == null) {
            userId = 1L;
        }
        this.setFieldValByName(this.autoFillProperties.getCreatedByField(), userId, metaObject);
        Date date = new Date();
        this.setFieldValByName(this.autoFillProperties.getCreateTimeField(), date, metaObject);
        this.setFieldValByName(this.autoFillProperties.getUpdateTimeField(), date, metaObject);
    }

    /**
     * 更新填充
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        // 更新人
        Long userId = this.getUserId();
        if (userId == null) {
            userId = 1L;
        }
        this.setFieldValByName(this.autoFillProperties.getLastUpdateByField(), userId, metaObject);
        this.setFieldValByName(this.autoFillProperties.getUpdateTimeField(), new Date(), metaObject);
    }
}